package com.zeroone.star.publish.controller;

import com.auth0.jwt.JWT;
import com.zeroone.star.publish.entity.*;
import com.zeroone.star.publish.service.impl.UserServiceImpl;
import com.zeroone.star.publish.utils.JwtUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @program: car-time-bank
 * @description:
 * @author: car
 * @create: 2024-03-06 09:28
 **/
@RestController
@RequestMapping("/token/user")
public class UserHandler {

    @Resource
    private UserServiceImpl userService;


    @GetMapping("/login")
    public TokenMessageDTO login(LoginUserDTO user) {
        TokenMessageDTO tokenMessageDTO = new TokenMessageDTO();

        try {
            Boolean loginRes = userService.login(Long.valueOf(user.getAccount()), user.getPassword());
            Map<String, String> payload = null;
            if (loginRes) {
                payload = new HashMap<>();
                User currentUser = userService.selectUserById(Long.valueOf(user.getAccount()));
                //用户登录成功后的信息放入payload
                payload.put("account", currentUser.getId().toString());
                payload.put("username", currentUser.getName());
            }
            //生成JWT令牌
            String token = JwtUtils.getToken(payload);
            tokenMessageDTO.setMessage("认证成功");
            tokenMessageDTO.setState(true);
            tokenMessageDTO.setToken(token);
        } catch (Exception e) {
            tokenMessageDTO.setMessage("认证失败");
            tokenMessageDTO.setState(false);
            tokenMessageDTO.setToken("11111");
        }
        return tokenMessageDTO;
    }
}
